<template>
  <div class="user-container">
    <bread></bread>

    <!-- 卡片 -->
    <el-card class="box-card">
      <div class="searchBox">
        <el-input placeholder="请输入内容"
                  v-model="paramsObj.query"
                  class="input-with-select">
          <el-button slot="append"
                     @click.native="getUsers"
                     icon="el-icon-search"></el-button>
        </el-input>

        <el-button type="primary"
                   class="usersBtn"
                   @click="dialogFormVisible = true">添加用户</el-button>
      </div>

      <!-- 表格 -->
      <el-table :data="tableData"
                style="width: 100%;margin-bottom:40px;"
                border>
        <el-table-column type="index"
                         label="#"
                         width="50"> </el-table-column>
        <el-table-column label="姓名"
                         prop="username"
                         width="180">
        </el-table-column>
        <el-table-column label="邮箱"
                         prop="email"
                         width="180">
        </el-table-column>
        <el-table-column label="电话"
                         prop="mobile"
                         width="180">
        </el-table-column>
        <el-table-column label="角色"
                         prop="role_name"
                         width="180">
        </el-table-column>
        <el-table-column label="状态"
                         width="180">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state"
                       @change="changeHandle(scope.row.id,scope.row.mg_state)"
                       active-color="#13ce66"
                       inactive-color="#ff4949">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini"
                       type="primary"
                       @click="handleEdit(scope.row)"
                       icon="el-icon-edit"></el-button>
            <el-button size="mini"
                       type="danger"
                       @click="handleDelete(scope.row.id)"
                       icon="el-icon-delete"></el-button>
            <el-tooltip class="item"
                        effect="dark"
                        content="分配权限"
                        placement="top">
              <el-button size="mini"
                         type="warning"
                         icon="el-icon-setting"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="paramsObj.pagenum"
                     :page-sizes="[1, 2, 3, 4]"
                     :page-size="paramsObj.pagesize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total">
      </el-pagination>

      <!-- 添加用户对话框 -->
      <el-dialog title="添加用户"
                 @close="close"
                 :visible.sync="dialogFormVisible">
        <el-form :model="form"
                 ref='refAdd'
                 :rules="rules">
          <el-form-item label="用户名"
                        prop="username"
                        label-width="120px">
            <el-input v-model="form.username"
                      autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="密码"
                        prop="password"
                        label-width="120px">
            <el-input v-model="form.password"
                      autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="邮箱"
                        prop="email"
                        label-width="120px">
            <el-input v-model="form.email"
                      autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="电话"
                        prop="mobile"
                        label-width="120px">
            <el-input v-model="form.mobile"
                      autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer"
             class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary"
                     @click="submitHandle">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 编辑用户对话框 -->
      <el-dialog title="编辑用户"
                 @close="close"
                 :visible.sync="dialogFormVisibleEdit">
        <el-form :model="formEdit"
                 ref='refEdit'
                 :rules="rules">
          <el-form-item label="用户名"
                        label-width="120px">
            <el-input :disabled="true"
                      v-model="formEdit.username"
                      autocomplete="off"></el-input>
          </el-form-item>

          <el-form-item label="邮箱"
                        prop="email"
                        label-width="120px">
            <el-input v-model="formEdit.email"
                      autocomplete="off"></el-input>
          </el-form-item>

          <el-form-item label="电话"
                        prop="mobile"
                        label-width="120px">
            <el-input v-model="formEdit.mobile"
                      autocomplete="off"></el-input>
          </el-form-item>

        </el-form>
        <div slot="footer"
             class="dialog-footer">
          <el-button @click="dialogFormVisibleEdit = false">取 消</el-button>
          <el-button type="primary"
                     @click="submitHandleEdit">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { usersApi, addUsersApi, delUsersApi, editUsersApi, editStateUsersApi } from '@/api'
export default {
  name: '',
  data () {
    // 自定义手机号的正则校验
    var validateMobile = (rule, value, callback) => {
      //  value===他表示的是表单的value值
      //  编写正则
      var reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
      if (!reg.test(value)) {
        callback(new Error('请输入合法的手机号'))
      } else {
        callback()
      }
    }
    return {
      tableData: [],
      paramsObj: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      total: 0,
      dialogFormVisible: false, // 添加对话框
      form: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 规则
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { min: 3, max: 15, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          /* 自定义的校验规则 */
          { validator: validateMobile, trigger: 'blur' }
        ]
      },
      /* 编辑 */
      dialogFormVisibleEdit: false,
      formEdit: {
        username: '1',
        email: '2',
        mobile: '3'
      }
    }
  },
  methods: {
    // 表格事件
    // 编辑
    handleEdit (row) {
      console.log(row)
      // 1-显示对话框
      this.dialogFormVisibleEdit = true
      // 2-将获取的当前行数据展示到页面上
      this.formEdit = row
    },
    // 删除
    handleDelete (id) {
      console.log(id)
      //  显示对话框提示
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        //  点击的是确认按钮
        //  发送请求删除用户
        const res = await delUsersApi(id)
        console.log(res)
        // 刷新数据
        this.getUsers()
      }).catch(() => {
        //  点击的是取消按钮
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 分页
    handleSizeChange (val) {
      console.log(`每页 ${val} 条`)
      this.paramsObj.pagesize = val
      //  重新根据页面数获取数据
      this.getUsers()
    },
    handleCurrentChange (val) {
      console.log(`当前页: ${val}`)
      this.paramsObj.pagenum = val
      //  重新根据页面数获取数据
      this.getUsers()
    },

    // 获取数据
    async getUsers () {
      const res = await usersApi(this.paramsObj)
      console.log(res)
      this.tableData = res.data.data.users
      // 获取总条数
      this.total = res.data.data.total
    },
    // 关闭对话框,清空添加表单数据
    close () {
      this.form = {
        username: '',
        password: '',
        email: '',
        mobile: ''
      }
      this.dialogFormVisible = false // 关闭对话框
      /* 清空编辑对话框中的数据 */
      this.formEdit = {
        username: '',
        email: '',
        mobile: ''
      }
      this.dialogFormVisibleEdit = false
    },
    // 添加用户
    submitHandle () {
      this.$refs.refAdd.validate(async (valid) => {
        if (valid) {
          const res = await addUsersApi(this.form)
          console.log(res)
          // 关闭对话框 清空数据
          this.close()
          // 刷新数据
          this.getUsers()
        }
      })
    },
    /* 点击编辑对话框中的确认按钮 */
    submitHandleEdit () {
      // 1-二次校验
      this.$refs.refEdit.validate(async (valid) => {
        if (valid) {
          const res = await editUsersApi(this.formEdit)
          console.log(res)
          // 3-关闭对话框 清空数据
          this.close()
          // 4-刷新数据
          this.getUsers()
        }
      })
    },

    /* 更改状态 */
    async changeHandle (id, state) {
      console.log(id, state, 999)
      await editStateUsersApi(id, state)
    }
  },
  created () {
    this.getUsers()
  }
}
</script>
<style lang="less" scoped>
.user-container {
  .box-card {
    .searchBox {
      margin: 15px 0- 20px;
      display: flex;
      .el-input {
        width: 400px;
        margin: 0 20px;
      }
    }
  }
}
.el-pagination {
  text-align: left;
}
</style>
